import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/index.vue'

// const store = JSON.parse()
const store = JSON.parse(localStorage.getItem('employee') || '{}')

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: Layout,
      redirect: '/user',
      children: [
        {
          path: 'user',
          name: 'user',
          component: () => import('@/views/emp/index.vue')
        },
        {
          path: 'category',
          name: 'category',
          component: () => import('@/views/category/index.vue')
        },
        {
          path: 'dish',
          name: 'dish',
          component: () => import('@/views/dishs/index.vue')
        },
        {
          path: 'addFood',
          name: 'addFood',
          component: () => import('@/views/addFood/index.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/test',
      name: 'test',
      component: () => import('@/views/test.vue')
    }
  ]
})

// 白名单
const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  if (store.empInfo && store.empInfo.token) {
    next()
    // 登录情况下
    // if (to.path === '/login') {
    //   next('/')
    // } else {
    //   页面刷新动态添加的路由为什么不会重置
    //   if (!store.token) {
    //     // 调用获取用户信息接口
    //     await store.dispatch('user/asyncGetUserBaseInfo')
    //     next(to.fullPath) // 相当于多做一次跳转 to.path带参数重定向没铺好的404页面
    //   } else {
    //     next()
    //   }
    // }
  } else {
    // 没有登录
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login`)
    }
  }
})
export default router
